<?php
/*******************************************************************************
 * @filename: payments_controller.php
 *
 * @author: immer_baldos
 *
 * @description: controller for payment model
 *
 * @history:
 *
 *   VERSION   DATE                   BY          NOTES
 *  ---------------------------------------------------------------
 *     1.0     September  9, 2009     immer       initial bake
 *
 *     2.0     September 12, 2009     immer       enable authetication
 *
 *     3.0     September 15, 2009     immer       add timstamp logic in add()
 *
 *     4.0     September 25, 2009     immer       add new() method
 *
 *     5.0     September 26, 2009     immer       add choose(), makeorder()
 *                                                ,finalize() methods
 *
 *
 ******************************************************************************/
class OrdersController extends AppController {

	var $name = 'Orders';
	var $helpers = array('Html', 'Form');
    var $components = array('Auth','Cookie', 'Session');

	function index() {
	    $this->Order->recursive = 0;

	    if ($this->Auth->user('role') == 'admin'){
            $this->set('orders', $this->paginate());
        } elseif ($this->Auth->user('role') == 'customer'){
            $this->set('orders', $this->paginate('Order', array('Order.customer_id' => $this->Auth->user('customer_id'))));
        } elseif ($this->Auth->user('role') == 'product officer'){
            $this->set('orders', $this->paginate('Order', array('Order.assigned_to' => 'APPROVED')));
        } elseif ($this->Auth->user('role') == 'finance'){
            $this->set('orders', $this->paginate('Order', array('Order.assigned_to' => 'NEW')));
        } elseif ($this->Auth->user('role') == 'sales'){
            //
            //TODO: implement sales filter here
            //
        }else {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect('/');
        }
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Order.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->loadModel('Product');
		$this->Product->recursive=0;
		$this->set('products', $this->Product->find('all'));

		$order = $this->Order->read(null, $id);
		$this->set('order', $order);
	}

	function choose($id = null) {
		if (!$id) {
		    //filter
			$this->Session->setFlash(__('Unknown Order Number.', true));
			$this->redirect('/');
		} else {
            //load available products
    	    $this->loadModel('Product');
		    $products = $this->Product->find('all', array('conditions' => array('Product.instock >' =>'0')));
		    $this->set(compact('products'));

            //load transaction list
    	    $this->loadModel('Transaction');
		    $transactions = $this->Transaction->find('all', array('conditions' => array('Transaction.order_id' => $id)));
		    $this->set(compact('transactions'));

            //load this order
		    $this->set('order', $this->Order->read(null, $id));
		}
	}

	function makeorder() {

	    //add filter for  0 cust id
        if($this->data['User']['customer_id']){
            $this->redirect('/');
        }

        //create default data
		$timestamp=getdate();
	    $defaultData = array( 'Order' => array( 'id'          => '',
	                                            'customer_id' => $this->Session->read('Auth.User.customer_id'),
	                                            'order_number'=> sprintf("%s%'03s%'02s%'02s%'02s",$timestamp['year'],$timestamp['yday'],$timestamp['hours'],$timestamp['minutes'],$timestamp['seconds']),
	                                            'print_count' => '0',
	                                            'print_date'  => '00-00-0000',
	                                            'created_by'  => $this->Session->read('Auth.User.username'),
	                                            'ship_via'    => ' ',
	                                            'sales_terms' => '0',
	                                            'sales_person'=> ' ',
	                                            'delivery_date'=> sprintf("%'02s-%'02s-%'04s",$timestamp['mon'],$timestamp['mday'],$timestamp['year']),
	                                            'approved' => '0',
	                                            'assigned_to' => 'EMPTY'
	                                            )
	                         );
        //save
        $this->Order->create();
        if ($this->Order->save($defaultData)) {
			$tmpList = $this->Order->find('all', array('conditions' => array('Order.order_number' => sprintf("%s%'03s%'02s%'02s%'02s",$timestamp['year'],$timestamp['yday'],$timestamp['hours'],$timestamp['minutes'],$timestamp['seconds']))));

		    //goto product chooser
			$this->redirect(array('action'=>'choose', $tmpList[0]['Order']['id']));
		} else {
			$this->flash('The Order could not be saved.', '/', 3);
		}
	}

	function add() {
		if (!empty($this->data)) {
			$this->Order->create();
			if ($this->Order->save($this->data)) {
				$this->Session->setFlash(__('The Order Saved.', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Order could not be saved. Please, try again.', true));
			}
		}

	    //add filter for  0 cust id
        if($this->data['User']['customer_id']){
            $this->redirect('/');
        }

		$timestamp=getdate();
		$this->set(compact('timestamp'));
		$customers = $this->Order->Customer->find('list');
		$this->set(compact('customers'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Order', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Order->save($this->data)) {
				$this->Session->setFlash(__('The Order has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Order could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Order->read(null, $id);
		}
		$customers = $this->Order->Customer->find('list');
		$this->set(compact('customers'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Order', true));
			$this->redirect('/');
		}

        //load available products
	    $this->loadModel('Product');

        //load transaction list
	    $this->loadModel('Transaction');
	    $transactions = $this->Transaction->find('all', array('conditions' => array('Transaction.order_id' => $id)));

        //uncommit stocks
        foreach ($transactions as $transaction){
	        $product = $this->Product->read( null ,$transaction['Transaction']['product_id']);
            $product['Product']['instock']+=$transaction['Transaction']['count'];
            $this->Product->save($product);
        }

		if ($this->Order->del($id)) {
			$this->Session->setFlash(__('Order deleted', true));
			$this->redirect('/');
		}
	}

    //add final details of order
	function finalize($id = null) {
		if (!$id && empty($this->data)) {
		    //filter
			$this->Session->setFlash(__('Unknown Order Number.', true));
			$this->redirect('/');
		}
		if (!empty($this->data)) {
		    $this->data['Order']['assigned_to']='NEW';

			if ($this->Order->save($this->data)) {
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Order could not be saved. Please, try again.', true));
			}
		}

		if (empty($this->data)) {
			$this->data = $this->Order->read(null, $id);
		    $this->data['Order']['assigned_to']='NEW';

            //load transaction list
    	    $this->loadModel('Transaction');
		    $transactions = $this->Transaction->find('all', array('conditions' => array('Transaction.order_id' => $id)));
		    $this->set(compact('transactions'));
		}
	}
}
?>